<?php 
include_once "header.php";
include_once "filters.php";
include_once "navbar.php";

//Variables a utilizar
//filters.php ya toma variables de filtros
$task=$_GET['task'];
$place_id=$_GET['place_id'];
$order=$_GET['order'];

//Si se pide logout
if($task == "logout") {
	User::logout();
  header("Location: index.php");
}
?>

<!DOCTYPE html>
<html>
  <head>
    <!--
    This site was based on the Represent.LA project by:
    - Alex Benzer (@abenzer)
    - Tara Tiger Brown (@tara)
    - Sean Bonner (@seanbonner)
    
    Create a map for your startup community!
    https://github.com/abenzer/represent-map
    -->
	<!-- 
	Ha sido modificado y adaptado por: 
	- dandolamurga (@dandolamurga_) 
	para localizar las Huelgas y Manifestaciones en España
	-->
    <title>Huelgas y Manifiestaciones</title>
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    
    <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:700|Open+Sans:400,700' type='text/css'>
    <link rel="stylesheet" href="./bootstrap/css/bootstrap.css" type="text/css" />
    <link rel="stylesheet" href="./bootstrap/css/bootstrap-responsive.css" type="text/css" />

    <script type="text/javascript" src="./scripts/jquery-1.9.1.min.js" charset=utf-8></script>
    <script type="text/javascript" src="./bootstrap/js/bootstrap.js" charset=utf-8></script>

    <link rel="stylesheet" href="./css/map.css?53452" type="text/css" />
    <!--<link rel="stylesheet" href="./css/mobile.css" type="text/css" media="only screen and (max-device-width: 480px)"  />-->

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="./scripts/label.js"></script>
    
    <link rel="stylesheet" href="./css/datepicker.css" type="text/css" />
    <script type="text/javascript" src="./scripts/bootstrap-datepicker.js"></script>

    <link rel="stylesheet" href="./css/bootstrap-select.css" type="text/css" />
    <script type="text/javascript" src="./scripts/bootstrap-select.js"></script>

    
    <? echo renderGoogleAnalytics() ?>
    
    <? //renderMapScript() ?>
    <script type="text/javascript">
      function getURLParameter(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
      }
      
      //URL Actions
      $(document).ready(function(){
        if(getURLParameter("task") == "modal_add"){
          $('#modal_add').modal('show');
        }
      });
      
      // places array: name, type (icon), lat, long, description, uri, address
      var places = new Array();
      var placesTitles = [];
      <?php

      
      $marker_id = 0;
      $list_places = array();
      switch ($order) {
        case 'type':
          $sqlOrder = "type, title";
          break;               
        default:
          $sqlOrder = "id DESC";
          break;
      }
      
      //Select place by uri
      if($place_id){
        $query = "SELECT id,id_user,type,title,description,approved,hashtag,uri,address,start_date,end_date,lat,lng FROM places WHERE id='$place_id'";
        $query_place = mysql_query($query);
        while($place_uri = mysql_fetch_assoc($query_place)){
          array_push($list_places, add_place($place_uri, $marker_id++, $todayDB, $place_id)); 
        }
      }
      
      //Select places by filters
      $query = "SELECT id,id_user,type,title,description,approved,hashtag,uri,address,start_date,end_date,lat,lng FROM places WHERE approved='1'";
      $query .= (!empty($filter_max_dateDB))?" AND start_date <= DATE('$filter_max_dateDB')":"";
      $query .= (!empty($filter_min_dateDB))?" AND end_date >= DATE('$filter_min_dateDB')":"";
      $query .= (!empty($filter_hashtag))?" AND hashtag LIKE '%$filter_hashtag%'":"";
      $query .= " ORDER BY $sqlOrder";
      
      $places = mysql_query($query);           
      
      if($places){
      while($place = mysql_fetch_assoc($places)) {
          if($place[id] != $place_id) {
            array_push($list_places, add_place($place, $marker_id++, $todayDB, $place_id));
          }             
        }
      }
         
      function add_place($place, $marker_id, $todayDB, $place_id){
        $finished = ( $place[end_date] < $todayDB);
      
        $place[title] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[title])));
        $place[description] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[description])));
        $place[hashtag] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[hashtag])));
        $place[uri] = addslashes(htmlspecialchars($place[uri]));
        $place[address] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[address])));
        $place[start_date] = htmlspecialchars_decode(addslashes(htmlspecialchars(convertDateToUserFormat($place[start_date]))));
        $place[end_date] = htmlspecialchars_decode(addslashes(htmlspecialchars(convertDateToUserFormat($place[end_date]))));
        $place[read_start_date] = toReadableDate($place[start_date],($place[start_date] == $place[end_date]));
        $place[read_end_date] = toReadableDate($place[end_date],true);
        $place[finished] = $finished;
        $place[highlight] = ($place[id] == $place_id);
        $place[marker_id] = $marker_id;
         
        echo "
           places.push(".json_encode($place).");";
        echo "
           placesTitles[".$marker_id."] = '".$place[title]."';";
           
        return $place;
      }
      ?>
    </script>
    
    <script type="text/javascript">
      var map;
      var infowindow = null;
      var gmarkers = [];
      var agent = "default";
      var zoomControl = true;
      var maxLengthDesc = <?php echo $place_desc_maxlength; ?>;
    
      // detect browser agent
      $(document).ready(function(){
        if(navigator.userAgent.toLowerCase().indexOf("iphone") > -1 || navigator.userAgent.toLowerCase().indexOf("ipod") > -1) {
          agent = "iphone";
          zoomControl = false;
        }
        if(navigator.userAgent.toLowerCase().indexOf("ipad") > -1) {
          agent = "ipad";
          zoomControl = false;
        }
        
      }); 
          
	   // set config.php map options
	   var zoomMarker = <?php echo $map_zoom_marker; ?>;
		
      // initialize map
      function initialize() {
        // set map styles
        var mapStyles = [
         {
            featureType: "road",
            elementType: "geometry",
            stylers: [
              { hue: "#8800ff" },
              { lightness: 100 }
            ]
          },{
            featureType: "road",
            stylers: [
              { visibility: "on" },
              { hue: "#91ff00" },
              { saturation: -62 },
              { gamma: 1.98 },
              { lightness: 45 }
            ]
          },{
            featureType: "water",
            stylers: [
              { hue: "#005eff" },
              { gamma: 0.72 },
              { lightness: 42 }
            ]
          },{
            featureType: "transit.line",
            stylers: [
              { visibility: "off" }
            ]
          },{
            featureType: "administrative.locality",
            stylers: [
              { visibility: "on" }
            ]
          },{
            featureType: "administrative.neighborhood",
            elementType: "geometry",
            stylers: [
              { visibility: "simplified" }
            ]
          },{
            featureType: "landscape",
            stylers: [
              { visibility: "on" },
              { gamma: 0.41 },
              { lightness: 46 }
            ]
          },{
            featureType: "administrative.neighborhood",
            elementType: "labels.text",
            stylers: [
              { visibility: "on" },
              { saturation: 33 },
              { lightness: 20 }
            ]
          }
        ];

		
        // set map options
        var myOptions = {
        	mapTypeId: google.maps.MapTypeId.ROADMAP,
          streetViewControl: false,
          mapTypeControl: false,
          panControl: false,
          zoomControl: zoomControl,
          styles: mapStyles,
          zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL,
            position: google.maps.ControlPosition.LEFT_CENTER
          }
        };
        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
        zoomLevel = map.getZoom();

        // prepare infowindow
        infowindow = new google.maps.InfoWindow({
          content: "holding..."
        });

        // only show marker labels if zoomed in
        google.maps.event.addListener(map, 'zoom_changed', function() {
          zoomLevel = map.getZoom();
          if(zoomLevel <= zoomMarker) {
            $(".marker_label").css("display", "none");
          } else {
            //$(".marker_label").css("display", "inline");
            $(".marker_label").css("display", "none");
          }
        });
        
				var bounds = new google.maps.LatLngBounds ();
				//  Coordenadas para incluir, como mínimo, la peninsula.
				var LatLngList = [];
				if(true){
					bounds.extend (new google.maps.LatLng (42,2.5));
					bounds.extend (new google.maps.LatLng (38,-8.5));
				}

        // add markers
        jQuery.each(places, function(i, place) {
          infowindow = new google.maps.InfoWindow({
            content: ""
          });

          // offset latlong ever so slightly to prevent marker overlap
          rand_x = Math.random();
          rand_y = Math.random();
          place['lat'] = parseFloat(place['lat']) + parseFloat(parseFloat(rand_x) / 6000);
          place['lng'] = parseFloat(place['lng']) + parseFloat(parseFloat(rand_y) / 6000);
          
          // show smaller marker icons on mobile
          if(agent == "iphone") {
            var iconSize = new google.maps.Size(16,19);
          } else {
            iconSize = null;
          }

          // build this marker
          var markerImage = new google.maps.MarkerImage("./images/icons/"+place['type']+".png", null, null, null, iconSize);
          var latLng = new google.maps.LatLng(place['lat'], place['lng']);
          
          var marker = new google.maps.Marker({
          	id:place['id'],
            position: latLng,
            map: map,
            title: '',
            clickable: true,
            infoWindowHtml: '',
            zIndex: 10 + i,
            icon: markerImage,
            type: place['type'],
            place: place
          });
          gmarkers.push(marker);

          //Extender límites para que incluya este marker
          bounds.extend(latLng);
          
          // add marker hover events (if not viewing on mobile)
          if(agent == "default") {
            google.maps.event.addListener(marker, "mouseover", function() {
              this.old_ZIndex = this.getZIndex(); 
              this.setZIndex(9999); 
              $("#marker"+i).css("display", "inline");
              $("#marker"+i).css("z-index", "99999");
            });
            google.maps.event.addListener(marker, "mouseout", function() { 
              //if (this.old_ZIndex && zoomLevel <= zoomMarker) {
              if (this.old_ZIndex) {
                this.setZIndex(this.old_ZIndex); 
                $("#marker"+i).css("display", "none");
              }
            }); 
          }

          // format marker URI for display and linking
          var markerURI = place['uri'];
          if(markerURI.substr(0,7) != "http://") {
            markerURI = "http://" + markerURI; 
          }
          var markerURI_short = markerURI.replace("http://", "");
          var markerURI_short = markerURI_short.replace("www.", "");
          
          //Formato para el hashtag
          var hashtag = place['hashtag'].replace('#','');;
          var hashtagURI = "https://twitter.com/intent/tweet?text=" + escape(place['hashtag']);
          
          //Formato para las fechas
          if(place['start_date'] != place['end_date']){
          	var fechas = "Fecha: "+place['read_start_date']+" - "+place['read_end_date'];
          }else{
          	var fechas = "Fecha: "+place['read_start_date']+".";
          }
					
					
          // add marker click effects (open infowindow)
          google.maps.event.addListener(marker, 'click', function () {
            <? 
              echo "id_user = '".User::id()."';".PHP_EOL; 
            ?>
            
            if(place["approved"] != '1'){
              icon_approved = "<img src='./images/warning.png' title='Pendiente de validar'></img>"
            }else{
              icon_approved = "";
            }
            
            if(<? echo (User::isAdmin())?"true ||":""; ?>(id_user == place["id_user"])){
              edit_link = "<a href='./admin/edit.php?place_id="+place['id']+"'><i class='icon-pencil'></i></a>";
            }else{
              edit_link = "";
            }
            infowindow.setContent(
              "<div class='marker_title'>"+icon_approved+place['title']+edit_link+"</div>"
              + "<div class='marker_date'>"+fechas+((place['finished'])?"<span class='label label-important'>Finalizada</span>":"")+"</div>"
              + ((place['uri'])?"<div class='marker_uri'><i class='icon-globe'></i><a target='_blank' href='"+markerURI+"'>"+markerURI_short+"</a></div>":"")
              + ((place['hashtag'])?"<div class='marker_hashtag'><i class='icon-share'></i><a target='_blank' href='"+hashtagURI+"'>"+place['hashtag']+"</a></div>":"")
              + "<div class='marker_desc'>"+place['description']+"</div>"
              + "<div class='marker_address'>"+place['address']+" <a href='#' onClick=\"goToMarkerById('"+place['id']+"')\">(zoom aquí)</a></div>"
            );
            infowindow.open(map, this);
          });

            
          // add marker label
          var label = new Label({
            map: map,
            id: i
          });
          label.bindTo('position', marker);
          label.set("text", place['title']);
          label.bindTo('visible', marker);
          label.bindTo('clickable', marker);
          label.bindTo('zIndex', marker);
        });

				
				google.maps.event.addListenerOnce(map, 'idle', function(){
          // do something only the first time the map is loaded
          <? 
          //si se specifica place_id
          if(!empty($place_id)){
            //Hacer zoom en place
            echo "if(!goToMarkerById($place_id))";
          }
          //Hacer zoom para incluir Todos los markers
          echo "{map.fitBounds (bounds);}";
          ?>
        });               
      } 

    
      // zoom to specific marker by place_id
      function goToMarkerById(place_id) {
        for (var i = 0; i < gmarkers.length; i++){
          if(gmarkers[i]['id'] == place_id){
          	goToMarker(i);
          	return true;
          }
        }
        return false;
      }


      // zoom to specific marker
      function goToMarker(marker_id) {
        if(marker_id > -1) {
          map.panTo(gmarkers[marker_id].getPosition());
          map.setZoom(zoomMarker);
          google.maps.event.trigger(gmarkers[marker_id], 'click');
        }
      }

      // toggle (hide/show) markers of a given type (on the map)
      function toggle(type) {
        if($('#filter_'+type).is('.inactive')) {
          show(type); 
        } else {
          hide(type); 
        }
      }

      // hide all markers of a given type
      function hide(type) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].type == type) {
            gmarkers[i].setVisible(false);
          }
        }
        $("#filter_"+type).addClass("inactive");
      }

      // show all markers of a given type
      function show(type) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].type == type) {
            gmarkers[i].setVisible(true);
          }
        }
        $("#filter_"+type).removeClass("inactive");
      }
      
      // toggle (hide/show) marker list of a given type
      function toggleList(type) {
        $("#list .list-"+type).toggle();
      }


      // hover on list item
      function markerListMouseOver(marker_id) {
        $("#marker"+marker_id).css("display", "inline");
      }
      function markerListMouseOut(marker_id) {
        $("#marker"+marker_id).css("display", "none");
      }

      google.maps.event.addDomListener(window, 'load', initialize);
      
     </script>
     
     <script> 
     $(document).ready(function(){
       // zoom to marker if selected in search typeahead list
       $('#search-input').typeahead({
        source: placesTitles, 
        highlighter: function(obj) {
          var place_index = jQuery.inArray(obj, placesTitles);
          var place = places[place_index];
          if(place['start_date'] != place['end_date']){
            var fechas = place['read_start_date']+" - "+place['read_end_date'];
          }else{
            var fechas = place['read_start_date'];
          }
        
          html = ''
               + "<div class='typeahead_wrapper'>"
               + "<img class='typeahead_photo' src='./images/icons/" + place["type"] + ".png' title='" + place["type"] + "' />"
               + "<div class='typeahead_labels'>"
               + "<div class='typeahead_primary'>" + obj + "</div>"
               + "<div class='typeahead_secondary'>" + fechas + ((place['finished'])?"<span class='label label-important label-small'>Finalizada</span>":"")+"</div>"
               + "</div>"
               + "</div>";
               
          return html;
        },
        updater: function(obj) {
          place_index = jQuery.inArray(obj, placesTitles);
          goToMarker(place_index);
          return obj;
        }
       });
     });
    </script>
    
    <? echo $head_html; ?>
  </head>
  <body>
    
    <!-- display error overlay if something went wrong -->
    <?php echo $error; ?>
    
    <!-- facebook like button code -->
	<div id="fb-root"></div>
	<script>(function(d, s, id) {
 	 	var js, fjs = d.getElementsByTagName(s)[0];
	  	if (d.getElementById(id)) return;
  		js = d.createElement(s); js.id = id;
  		js.src = "//connect.facebook.net/es_LA/all.js#xfbml=1";
  		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));</script>
    <!-- twitter button code -->
  <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
  
    
		<? renderNavBar("main") ?>
        
    <div class="container-fluid">
      <div class="row-fluid clearfix" id="main-content">
        <div class="span3" id="">
        	
          <input type="text" class="input-block-level" id="search-input" placeholder="Buscar..." data-provide="typeahead" autocomplete="off" />
 	        <div class="order-by">
	        	<span>Ordenar: </span>
  	        	<span class="dropdown">
  	            <a class="dropdown-toggle" role="button" data-toggle="dropdown" href="#"><? echo ($order=="type")?"Por tipo":"Por nuevo"; ?> <b class="caret"></b></a>
                <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
    	            <li><a tabindex="-1" href="index.php?order=type<? echo ($filter_date)?"&filter_date=$filter_date":""; ?>">Por tipo</a></li>
                  <li><a tabindex="-1" href="index.php?<? echo ($filter_date)?"&filter_date=$filter_date":""; ?>">Por nuevo</a></li>
                </ul>
              </span>
              <script>
                $('.dropdown-toggle').dropdown()
              </script>
	        	<!--<span class="pull-right"><i class="icon-share"></i></span>-->
	        </div>
         	<div class="list-container">
        		<ul>
         <?php
          $marker_id = 0;
          foreach($list_places as $place) {
	          	if($place[start_date] != $place[end_date]){
		          	$fechas = $place[read_start_date]." - ".$place[read_end_date];
		          }else{
		          	$fechas = $place[read_start_date];
		          }
						  
            	echo "
                  <li class='bullet-".$place[type].(($place[highlight])?" highlight":"")."'>
                    <div onMouseOver=\"markerListMouseOver('".$place[marker_id]."')\" onMouseOut=\"markerListMouseOut('".$place[marker_id]."')\" onClick=\"goToMarker('".$place[marker_id]."');\">
                      <div class='title' title='".$place[title]."'>".$place[title]."</div>
                      <div class='date'>". $fechas . (($place['finished'])?"<span class='label label-important label-small'>Finalizada</span>":"")."</div>
                    </div>
                  </li>";
              $marker_id++;
          }
          echo "
            
            ";
          
        ?>
        		</ul>
          </div><!--/.list -->
        </div><!--/span-->
        <div class="span9">
        	<div class="row-fluid"> <!--accordion-body collapse" id="collapseSearch">
		    		<div class="accordion-inner">-->
			    		<div class="span12">
			    			<!--<input type="text" class="input-block-level" id="select-location" placeholder="Provincia..." data-provide="typeahead" autocomplete="off" />-->
			    		
			    			<?php
			  					$query = "SELECT COUNT(*) AS contador FROM places WHERE approved='1' AND start_date <= DATE('$todayDB') AND end_date >= DATE('$todayDB')" ;
			   					$today_count = mysql_query("$query");
			   					$marker_today = mysql_fetch_assoc($today_count);   
			   			
			  					$query = "SELECT COUNT(*) AS contador FROM places WHERE approved='1' AND start_date <= DATE('$tomorrowDB') AND end_date >= DATE('$tomorrowDB')" ;
			   					$tomorrow_count = mysql_query("$query");
			   					$marker_tomorrow = mysql_fetch_assoc($tomorrow_count);   
			   			
							  	$query = "SELECT COUNT(*) AS contador FROM places WHERE approved='1' AND start_date <= DATE('$weekDB') AND end_date >= DATE('$todayDB')" ;
			   					$week_count = mysql_query("$query");
			   					$marker_week = mysql_fetch_assoc($week_count);   
							
							  	$query = "SELECT COUNT(*) AS contador FROM places WHERE approved='1' AND end_date >= DATE('$todayDB')" ;
			   					$next_count = mysql_query("$query");
			   					$marker_next = mysql_fetch_assoc($next_count);   
							
									$count_today = $marker_today[contador];
									$count_tomorrow = $marker_tomorrow[contador];
									$count_week = $marker_week[contador];
									$count_next = $marker_next[contador];
									
                  $order_filter = ($order)?"&order=$order":"";
			          ?>
			          
	              
		            <form name="formFilterDate" id="formFilterDate">
		            	<span class="filter-label">Fecha</span>
			          
		            	<select name="filter" class="input-medium selectpicker" data-width="180px" onChange="document.location.href=document.formFilterDate.filter.options[document.formFilterDate.filter.selectedIndex].value">
									  <option value="#" class="option_neutral"><strong>Elegir Rango...</strong></option>
									  <option value="index.php" <?=($filter_date=="")?" selected":"";?> data-subtext="(<?php echo $count_next ?>)">Próximas</option>
									  <option value="index.php?filter_date=today<?=$order_filter?>" <?=($filter_date=="today")?" selected":"";?> data-subtext="(<?php echo $count_today ?>)">Hoy</option>
									  <option value="index.php?filter_date=tomorrow<?=$order_filter?>" <?=($filter_date=="tomorrow")?" selected":"";?> data-subtext="(<?php echo $count_tomorrow ?>)">Mañana</option>
									  <option value="index.php?filter_date=week<?=$order_filter?>" <?=($filter_date=="week")?" selected":"";?> data-subtext="(<?php echo $count_week ?>)">Próx. 7 días</option>
										<optgroup label="Historial">
											<option value="index.php?filter_date=yesterday<?=$order_filter?>" <?=($filter_date=="yesterday")?" selected":"";?>>Ayer</option>
											<option value="index.php?filter_date=lastweek<?=$order_filter?>" <?=($filter_date=="lastweek")?" selected":"";?>>El última semana</option>
											<option value="index.php?filter_date=lastmonth<?=$order_filter?>" <?=($filter_date=="lastmonth")?" selected":"";?>>El último mes</option>
											<option value="index.php?filter_date=lastyear<?=$order_filter?>" <?=($filter_date=="lastyear")?" selected":"";?>>El último año</option>
										</optgroup>
									</select> 
								<span class="filter-label">Desde</span>
			          <input type="text" class="input-small" id="filter_start_date" value="<?php echo $filter_min_date; ?>" placeholder="dd-mm-aaaa">
			    		
					 			<span class="filter-label">Hasta</span>
			          <input type="text" class="input-small" id="filter_end_date" value="<?php echo $filter_max_date; ?>" placeholder="dd-mm-aaaa">
			          <button class="btn btn-info" id="btn-filter-date" data-filter="<?=$order_filter?>"><i class="icon-search"></i></button>
								</form>
							
		          </div>
		          
			    		<script type="text/javascript" src="./scripts/config-filterdatepicker.js"></script>
			    		<script>
			    			$('.selectpicker').selectpicker();
			    		</script>
    
			    		
		    		<!--</div>-->
		    	</div><!--/row--> 
		    	<div class="row-fluid">
          	<div id="map_canvas"></div>
          </div>
        </div><!--/span-->
      </div><!--/row-->  
      <div class="row-fluid clearfix">
       	<div class="span3">
					<a class="twitter-timeline"  href="https://twitter.com/mnfstt"  data-widget-id="319957976087662593">Tweets por @mnfstt</a>
					<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
 					<p><div class="fb-like-box" data-href="https://www.facebook.com/Manifiestate" data-width="283" data-show-faces="true" data-stream="true" data-header="true"></div>      
        </div><!--/span-->
        <div class="span9" id="info">
	        <h3>Acerca Manifiestate.net</h3>
	        <p>Manifiestate.net se ha creado con el objetivo de <strong>poner en conocimiento todas las protestas</strong> que se están llevando a cabo en España.</p>
			  <p>A menudo nos ocurre que solamente conocemos las protestas más representativas del país, aquéllas a las que los medios de comunicación dan voz. No obstante, existen un gran número de protestas que desconocemos y que dichos colectivos necesitan que se sepa por lo qu están luchando.</p>
			  <p>Con ayuda de los sindicatos y asociaciones estamos formando un mapa con el que mantener actualizadas aquellas protestas que se están llevando a cabo o bien están programadas. De esta forma, <strong>todo el mundo podrá saber</strong> qué protestas hay cerca suyo y se le podrá dar más difusión a través de las redes sociales, permitiéndonos organizarnos de mejor manera y conocer la magnitud de los movimientos en el país.</p>
	        <p>Pongamos todas las protestas en el mapa!!</p>
	        <p>¿Preguntas? ¿Sugerencias? ¿Eres un sindicato/asociación y quieres colaborar? Contacta con: <a href="http://www.twitter.com/mnfstt" target="_blank">@mnfstt</a> o en <a>info@manifiestate.net</a></p>
	        <h3>Próximos objetivos</h3>
	        <p>Tras haber actualizado por completo la apariencia de la página y añadido algunas de las sugerencias aportadas por los usuarios queremos seguir con el proyecto hacia adelante y seguir añadiéndole mejoras.</p>
	        <p>Nuestra intención no es ser nosotros quienes subamos las protestas. Queremos que tanto los <strong> sindicados</strong>, <strong> organizaciones</strong> y <strong> plataformas ciudadanas</strong> se registren y hagan uso de la herramienta y su difusión. Queremos sencillamente ser la plataforma que les ayude a transmitir su mensaje así como la plataforma que ayude al ciudadano a estar al día de lo que está ocurriendo a su alrededor y pueda implicarse.</p>
	        <p>Nos marcamos como próximo objetivo conseguir realizar una <strong>página por protesta</strong> en la que se pueda mostrar mucha más información de la convocatoria, se puedan subir manifiestos, fotos, enlaces y comentarios de los usuarios. Con ello conseguiremos más interés tanto en los ciudadanos como en los organizadores logrando mantener la comunidad viva entre todos.</p>
	        <p>Esperamos conseguir nuestro objetivo y estamos abiertos a todas la sugerencias que nos mandéis por twitter, por email o incluso por el botón de sugerencias que tenéis justo debajo. Como se puede ver, hemos hecho caso de momento a todas las que se nos han planteado.</p>

        	<p>
       		<a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.manifiestate.net" data-text="Pongamos todas las huelgas y manifestaciones en el mapa:" data-via="mnfstt" data-count="yes">Tweet</a>
          <!--<div class="fb-like" data-href="http://www.manifiestate.net" data-send="false" data-layout="button_count" data-width="100" data-show-faces="true" data-font="tahoma"></div>-->
			  </p>

        </div><!--/span-->
       </div><!--/row-->
      
     <hr>
      <footer>           
      </footer>
    </div><!--/.fluid-container-->      
                 
    <? echo renderUserVoice(); ?>
    
    <!-- modal_add event  -->  
    <div class="modal hide" id="modal_add">
 
      <form action="add.php" id="modal_addform" class="form-horizontal">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h3>Introduce una protesta!</h3>
        </div>
        <div class="modal-body">
			<?php if( !User::isAutentified() ) { ?>
        <p>Ayúdanos a colocar las protestas en el mapa dándonos los datos que se piden a continuación. Esta protesta estará gestionada por los administradores. Si perteneces a algún sindicato u organización te recomendamos que <a href="login.php" target="_blank">entres con tu usuario</a> para que puedas tener el control de ella.</p>
			<?php } ?> 
          <div id="result"></div>
          <fieldset>
			<?php if( !User::isAutentified() ) { ?>
            <div class="control-group">
              <label class="control-label" for="add_contact_email">Email contacto</label>
              <div class="controls">
                <input type="text" class="input-xlarge" name="contact_email" id="add_contact_email" maxlength="100" autocomplete="off">
              </div>
            </div>
			<?php } ?>           
          
          
            <div class="control-group">
              <label class="control-label" for="add_title">Nombre Protesta</label>
              <div class="controls">
                <input type="text" class="input-xlarge" name="title" id="add_title" maxlength="100" autocomplete="off">
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="input01">Tipo de protesta</label>
              <div class="controls">
                <select name="type" id="add_type" class="input-xlarge">
                	<?php
                	foreach($places_types as $type)
					{
						echo "<option value=\"".$type[0]."\">".$type[1]."</option>";
					}
					?>
                </select>
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="add_address">Ubicación</label>
              <div class="controls">
                <input type="text" class="input-xlarge" name="address" id="add_address"><button class="btn btn-info" id="search-address"><i class="icon-search"></i></button>
                <p class="help-block">
                  Suele ser la <b>calle completa (incluyendo ciudad y CP)</b> de la convocatoria.
                  Si funciona en Google Maps, funcionará aquí.
                </p>
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="add_description">Descripción</label>
              <div class="controls">
                <textarea class="input input-xlarge" id="add_description" maxlength="<?php echo $place_desc_maxlength; ?>" name="description"></textarea>
                <p class="help-block">
                  Breve y concisa descripción. ¿Qué se reivindica y por qué? ¿Qué está ocurriendo? Max <?php echo $place_desc_maxlength; ?> carac.
                </p>
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="start_date">Fecha Inicio</label>
              <div class="controls">
                <input type="text" class="input-small" name="start_date" id="start_date" placeholder="dd-mm-aaaa">
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="end_date">Fecha Fin</label>
              <div class="controls">
                <input type="text" class="input-small" name="end_date" id="end_date" placeholder="dd-mm-aaaa">
                <p class="help-block">
                  Fecha en formato dd-mm-aaaa. Ej: 21-08-2012
                </p>
              </div>
            </div>         
            <div class="control-group">
              <label class="control-label" for="add_uri">URL del sitio</label>
              <div class="controls">
                <input type="text" class="input-xlarge" id="add_uri" name="uri" placeholder="http://">
                <p class="help-block">
                  Página web, grupo de Facebook,...
                </p>
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="add_uri">Hashtag en Twitter</label>
              <div class="controls">
                <input type="text" class="input-xlarge" id="add_hashtag" name="hashtag" placeholder="#">
                <p class="help-block">
                  Etiqueta en Twitter. Ej: #15M
                </p>
              </div>
            </div>
          </fieldset>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" type="submit" id="btn-submit">Añadir para su revisión</button>
          <button class="btn btn-success" id="btn-refresh" >Añadir otra protesta</button>
          <a href="#" class="btn" data-dismiss="modal" style="float: right;">Cerrar</a>
        </div>
      </form>

    </div>

    <script type="text/javascript" src="./scripts/config-datepicker.js"></script>
    
    <script>
      $(document).ready(function(){
        $("#modal_addform #btn-refresh").css("display", "none");
        $("#modal_addform #btn-refresh").css("float", "left");
        $("#modal_addform #btn-refresh").click( function (event){
          event.preventDefault();
          $("#modal_addform").attr('action', '');
        	window.location.href="index.php?task=modal_add";
        });
                 
      });
    
     $("#modal_addform #start_date").focus(function (){
     	 topOffset = 2000; 
       $("#modal_addform .modal-body").scrollTop(topOffset);
     });
     $("#modal_addform #end_date").focus(function (){
     	 topOffset = 2000;
       $("#modal_addform .modal-body").scrollTop(topOffset);
     });
     
     $("#search-address").click(function(e){
    		var address = $("#add_address").val();
    		e.preventDefault();
    		window.open("https://maps.google.com/maps?q="+address, "search-address");
    	});
    
      // add modal form submit
      $("#modal_addform").submit(function(event) {
        event.preventDefault(); 
        $("#modal_addform #btn-submit").attr("disabled", true);
        
        // get values
        var $form = $( this ),
        		contact_email = $form.find( '#add_contact_email' ).val(),
            title = $form.find( '#add_title' ).val(),
            type = $form.find( '#add_type' ).val(),
            address = $form.find( '#add_address' ).val(),
            start_date = $form.find( '#start_date' ).val(),
            end_date = $form.find( '#end_date' ).val(),
            uri = $form.find( '#add_uri' ).val(),
            description = $form.find( '#add_description' ).val(),
            hashtag = $form.find( '#add_hashtag' ).val(),
            url = $form.attr( 'action' );
         
        // send data and get results
        $.post( url, {contact_email: contact_email, title: title, type: type, start_date : start_date, end_date : end_date, address: address, uri: uri, description: description, hashtag: hashtag },
          function( data ) {
            
            // if submission was successful, show info alert
            if(data == "success") {
              	$("#modal_addform #result").html("Hemos recibido su protesta y en breve será revisada. Gracias!"); 
              	$("#modal_addform #result").addClass("alert alert-info");
              	$("#modal_addform p").css("display", "none");
              	$("#modal_addform fieldset").css("display", "none");
              	$("#modal_addform #btn-submit").css("display", "none");
 			  	 	$("#modal_addform #btn-refresh").css("display", "block");
 			  	
 			  	// if it is an advise, show mail sent		
	         } else if(data == "mail_sent") {
            	$("#modal_addform #result").html("Hemos enviado un email al Administrador y será breve será revisada. Gracias!"); 
              	$("#modal_addform #result").addClass("alert alert-info");
              	$("#modal_addform p").css("display", "none");
              	$("#modal_addform fieldset").css("display", "none");
              	$("#modal_addform #btn-submit").css("display", "none");
 			  		$("#modal_addform #btn-refresh").css("display", "block");
 			  			
            // if submission failed, show error
            } else {
              	$("#modal_addform #result").html(data); 
              	$("#modal_addform #result").addClass("alert alert-danger");
              	$("#modal_addform #btn-submit").attr("disabled", false);
              	$("#modal_addform .modal-body").stop().scrollTop(0); 
            	}
          }
        );
      });
    </script>    
  </body>
</html>
